﻿using B.S.RbacData.Domain;
using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using B.S.RbacData.Write.API.Applications.Commands.RBAC;
using MediatR;
using System.Transactions;

namespace B.S.RbacData.Write.API.Applications.Commandhandlters.RBAC
{

    /// <summary>
    /// 添加角色信息处理
    /// </summary>
    public class AddRolePermissionCommandhandlter : IRequestHandler<AddRolePermissionCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<RoleModel> roleRep;
        private readonly IBaseRepository<RolePermissionModel> rolepermissionRep;
        private readonly ILogger<AddRolePermissionCommandhandlter> logger;

        public AddRolePermissionCommandhandlter(IBaseRepository<RoleModel> roleRep, IBaseRepository<RolePermissionModel> rolepermissionRep,ILogger<AddRolePermissionCommandhandlter> logger)
        {
            this.roleRep = roleRep;
            this.rolepermissionRep = rolepermissionRep;
            this.logger = logger;
        }

        public async Task<ApiResult<int>> Handle(AddRolePermissionCommand request, CancellationToken cancellationToken)
        {
            var role = roleRep.GetAll().FirstOrDefault(x => x.RoleName == request.RoleName);

            if(role!= null)
            {
                return new ApiResult<int>()
                {
                    code = ResultEnumCode.fails,
                    message = "角色名称重复",
                    data = 0
                };
            }

            //分布式事务
            using(var tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    //添加角色
                    RoleModel role1 = new RoleModel
                    {
                        RoleName = request.RoleName,
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now,
                        IsState = true,
                        IsDeleted = false
                    };
                    await roleRep.AddAsync(role1);

                    //等待确保角色ID已生成
                    Thread.Sleep(100);

                    //添加角色权限信息
                    foreach (var permissionId in request.PermissionId)
                    {
                        var rolepermission = new RolePermissionModel
                        {
                            PermissionId = permissionId,
                            RoleId = role1.ID,
                            CreateTime = DateTime.Now,
                            UpdateTime = DateTime.Now,
                            IsState = true,
                            IsDeleted = false
                        };
                        await rolepermissionRep.AddAsync(rolepermission);
                    }

                    //提交事务
                    tran.Complete();
                }
                catch (Exception ex)
                {
                    //事务回滚
                    tran.Dispose();
                    logger.LogError($"添加角色权限异常: {ex.Message}");
                    throw;
                }
            }

            return new ApiResult<int>()
            {
                code = ResultEnumCode.Ok,
                message = "添加成功",
                data = 1
            };
        }
    }
}
